package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 传感器
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/device/welding")
public class DeviceWeldingController extends BaseController {

    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private ShopService shopService;
    @Resource
    private FsrDeviceService fsrDeviceService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private CityService cityService;
    @Resource
    private FsrAssetsService fsrAssetsService;
    @Resource
    private PianqusService pianqusService;

    @Value("${projecturl.uploadPath}")
    private String uploadPath;

    @Value("${projecturl.imgurl}")
    private String imgUrl;

    @Log("查询设备页面")
    @GetMapping()
    @RequiresPermissions("module:deviceWelding:deviceWelding")
    String device(Model model) {
        model.addAttribute("isSelf",0);
        model.addAttribute("deviceType",0);
        return "module/device/welding/welding";
    }

    @Log("查询设备页面")
    @GetMapping("/plasma")
    @RequiresPermissions("module:deviceWelding:deviceWelding")
    String devicePlasma(Model model) {
        model.addAttribute("isSelf",0);
        model.addAttribute("deviceType",1);
        return "module/device/welding/welding";
    }


    @Log("查询设备页面")
    @GetMapping("/shop/{deviceType}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String shopList1(Model model,@PathVariable("deviceType") Integer deviceType) {
        UserDO user = getUser();
        model.addAttribute("shopType",6);
        model.addAttribute("deviceType",deviceType);

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);

        return "module/device/welding/shop";
    }


    @Log("查询设备页面")
    @GetMapping("/{shopId}")
    @RequiresPermissions("module:deviceWelding:deviceWelding")
    String device(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("isSelf",0);
        model.addAttribute("shopId",shopId);
        return "module/device/welding/welding";
    }


    @Log("查询设备页面")
    @GetMapping("/{shopId}/{deviceType}")
    @RequiresPermissions("module:deviceWelding:deviceWelding")
    String device(Model model, @PathVariable("shopId") Integer shopId,@PathVariable("deviceType") Integer deviceType) {
        model.addAttribute("isSelf",0);
        model.addAttribute("shopId",shopId);
        model.addAttribute("deviceType",deviceType);
        return "module/device/welding/welding";
    }


    @Log("查询设备页面")
    @GetMapping("/self")
    @RequiresPermissions("module:deviceWelding:deviceWelding")
    String deviceSelf(Model model) {
        model.addAttribute("isSelf",1);
        return "module/device/welding/welding";
    }

    /**
     * 获取当前的设备列表
     */
    @Log("获取当前的设备列表")
    @ResponseBody
    @PostMapping("/getDeviceList")
    public R getDeviceList() {
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<DeviceWelding> qw = new QueryWrapper<>();
        qw.isNotNull("lng");
        qw.isNotNull("lat");
        List<DeviceWelding> devices = deviceWeldingService.list(qw);
        map.put("devices",devices);
        return R.ok(map);
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions(value = {"module:deviceWelding:deviceWelding"}, logical = Logical.OR)
    public DataTableLayUI<DeviceWelding> list(DataTableLayUI<DeviceWelding> condition) {
        UserDO user = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String deviceNum = null;
        if(map != null) {
            deviceNum = StrUtil.isNotEmpty(map.get("search_like_keyword").toString()) ? map.get("search_like_keyword").toString():null;
        }
        Integer isSelf = StrUtil.isNotEmpty(map.get("search_eq_isSelf").toString()) ? Integer.parseInt(map.get("search_eq_isSelf").toString()):0;
        Integer shopId = StrUtil.isNotEmpty(map.get("search_eq_shopId").toString()) ? Integer.parseInt(map.get("search_eq_shopId").toString()):0;
        Integer deviceType = StrUtil.isNotEmpty(map.get("search_eq_deviceType").toString()) ? Integer.parseInt(map.get("search_eq_deviceType").toString()) : 0;

        Map<String,Object> map1 = new HashMap<>();

        map1.put("device_type",deviceType);

        if(deviceNum != null){
            map1.put("device_num",deviceNum);
        }
        map1.put("is_self",isSelf);

        if(user.getUserType() == 10){
            map1.put("shop_id", user.getShopId());
        } else if(user.getUserType() == 2){//集团用户
            map1.put("group_id", user.getGroupId());
        } else if(user.getUserType() == 3){//片区管理员用户
            map1.put("pianqu_id", user.getPianquId());
        } else if(user.getUserType() == 4){//分厂管理员用户
            map1.put("shop_id", user.getShopId());
        } else{
        }
        if(shopId > 0){
            map1.put("shop_id", shopId);
        }


        Page<DeviceWelding> page = deviceWeldingService.getPage(condition);
        List<DeviceWelding> list = deviceWeldingService.getPageByUserId(page,map1);
        DataTableLayUI<DeviceWelding> dt = deviceWeldingService.pageSearchCustom(page,list,condition);
        List<DeviceWelding> devices = dt.getData();
        for (DeviceWelding device : devices){
            device.setQrCodeUrl( imgUrl + device.getQrCodeUrl());
            Shop shop = shopService.findById(device.getShopId());
            if(shop!=null){
                device.setShopName(shop.getShopName());
            }
            QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
            qw.eq("device_id", device.getId());
            qw.last("limit 1");
            FsrDevice fsrDevice = fsrDeviceService.getOne(qw);
            if(fsrDevice!= null){

                QueryWrapper<FsrAssets> qwAsset = new QueryWrapper<>();
                qwAsset.eq("asset_id", fsrDevice.getAssetId());
                qwAsset.last("limit 1");
                FsrAssets assets = fsrAssetsService.getOne(qwAsset);
                if(assets!= null){
                    device.setFsrAssets(assets);
                }

                device.setFsrDevice(fsrDevice);
            }
        }
        return dt;
    }

    @Log("新增设备页面")
    @GetMapping("/add")
    @RequiresPermissions(value = {"module:deviceWelding:add"}, logical = Logical.OR)
    String add(Model model) {
        DeviceWelding device = new DeviceWelding();

        device.setProvId(15);
        model.addAttribute("device", device);

        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
        qw.eq("device_id",0);
        List<FsrDevice> fsrDevices = fsrDeviceService.list(qw);
        if(CollUtil.isNotEmpty(fsrDevices)){
            for (FsrDevice device1 : fsrDevices){

                QueryWrapper<FsrAssets> qwAsset = new QueryWrapper<>();
                qwAsset.eq("asset_id", device1.getAssetId());
                qwAsset.last("limit 1");
                FsrAssets assets = fsrAssetsService.getOne(qwAsset);
                if(assets!= null){
                    device1.setFsrAssets(assets);
                }
            }
        }
        model.addAttribute("fsrDevices", fsrDevices);


        model.addAttribute("provId", 15);
        List<Province> provinces = provinceService.list();
        model.addAttribute("provinces", provinces);

        List<City> cityList = cityService.selectListByColumn("province_id",15);
        model.addAttribute("cityList", cityList);

        return "module/device/welding/detail";
    }

    @Log("新增设备页面")
    @GetMapping("/add/{isSelf}")
    @RequiresPermissions(value = {"module:deviceWelding:add"}, logical = Logical.OR)
    String addNew(Model model,@PathVariable("isSelf") Integer isSelf) {
        DeviceWelding device = new DeviceWelding();
        device.setIsSelf(isSelf);
        device.setProvId(15);
        model.addAttribute("device", device);

        List<Shop> companies = shopService.list();
        model.addAttribute("companies", companies);

        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
//        qw.eq("device_id",0);
        List<FsrDevice> fsrDevices = fsrDeviceService.list(qw);
        if(CollUtil.isNotEmpty(fsrDevices)){
            for (FsrDevice device1 : fsrDevices){
                QueryWrapper<FsrAssets> qwAsset = new QueryWrapper<>();
                qwAsset.eq("asset_id", device1.getAssetId());
                qwAsset.last("limit 1");
                FsrAssets assets = fsrAssetsService.getOne(qwAsset);
                if(assets!= null){
                    device1.setFsrAssets(assets);
                }
            }
        }
        model.addAttribute("fsrDevices", fsrDevices);


        model.addAttribute("provId", 15);
        List<Province> provinces = provinceService.list();
        model.addAttribute("provinces", provinces);

        List<City> cityList = cityService.selectListByColumn("province_id",15);
        model.addAttribute("cityList", cityList);


        return "module/device/welding/detail";
    }


    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @ResponseBody
    @RequestMapping("/resetQrCode")
    @RequiresPermissions(value = {"module:deviceWelding:edit"}, logical = Logical.OR)
    public R resetQrCode(@Valid DeviceWelding device) {
        device = deviceWeldingService.findById(device.getId());
        try{
            String qrCode = "";
            String fileName = device.getDeviceName() + "_" + device.getId() +".jpg";
//            String content = "{\"qrtype\":\"electric_welding\",\"id\":" + device.getId()+"}";
            String content = "https://en.zcchengyi.com/welding/qr?id=" + device.getId();
//            Aes aes = new Aes();
//            content = aes.encrypt(content);
            System.out.println("content:  "+ content);
            String ss = device.getShopId()+"";
            if(device.getIsSelf() == 1){
                ss = "self";
            }
            //上传头像到OSS
            String img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_DEVICE_WELDING_PHOTOS) + ss + "/"  + fileName;
            QRCodeUtilEx.createQrCodeImg(content, "NO. " + device.getDeviceNo(), null,
                    uploadPath +"/"+ img_key, true);
            qrCode = img_key;
            device.setQrCodeUrl(qrCode);
        }catch (Exception e){
            e.printStackTrace();
        }

        boolean bl = deviceWeldingService.updateById(device);
        if(bl){
            return R.ok();
        }
        return R.error();
    }


    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @ResponseBody
    @GetMapping("/cityList/{provId}")
    public R cityList(@PathVariable("provId") Integer provId) {
        Map<String,Object> map = new HashMap<>();
        List<City> cityList = cityService.selectListByColumn("province_id",provId);
        map.put("cityList",cityList);
        return R.ok(map);
    }


    /**
     * 下载二维码
     */
    @Log("下载二维码")
    @GetMapping("/downloadQrCode/{qrCodeId}")
    public void download(@PathVariable("qrCodeId") Integer qrCodeId, HttpServletResponse response) {
        DeviceWelding qrCode = deviceWeldingService.findById(qrCodeId);
        if(qrCode!=null){
            FileUtils.download(uploadPath + qrCode.getQrCodeUrl(),response);
        }
    }

    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions(value = {"module:deviceWelding:edit"}, logical = Logical.OR)
    String edit(@PathVariable("id") Integer id, Model model) {
        DeviceWelding device = deviceWeldingService.findById(id);
        if(device.getProvId() == null){
            device.setProvId(15);
        }
        model.addAttribute("device", device);

        Shop shop = shopService.findById(device.getShopId());
        if(shop!= null){
            device.setShopName(shop.getShopName());
        }
        List<Shop> companies = shopService.list();
        model.addAttribute("companies", companies);

        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
//        qw.eq("device_id",0);
        List<FsrDevice> fsrDevices = fsrDeviceService.list(qw);
        if(CollUtil.isNotEmpty(fsrDevices)){
            for (FsrDevice device1 : fsrDevices){
                QueryWrapper<FsrAssets> qwAsset = new QueryWrapper<>();
                qwAsset.eq("asset_id", device1.getAssetId());
                qwAsset.last("limit 1");
                FsrAssets assets = fsrAssetsService.getOne(qwAsset);
                if(assets!= null){
                    device1.setFsrAssets(assets);
                }
            }
        }
        model.addAttribute("fsrDevices", fsrDevices);

        model.addAttribute("provId", device.getProvId());
        List<Province> provinces = provinceService.list();
        model.addAttribute("provinces", provinces);

        List<City> cityList = cityService.selectListByColumn("province_id",device.getProvId());
        model.addAttribute("cityList", cityList);

        return "module/device/welding/detail";
    }


    @Log("预览设备页面")
    @GetMapping("/view/{id}")
    @RequiresPermissions(value = {"module:deviceWelding:edit"}, logical = Logical.OR)
    String view(@PathVariable("id") Integer id, Model model) {
        DeviceWelding device = deviceWeldingService.findById(id);
        if(device!= null){
            Shop shop = shopService.findById(device.getShopId());
            if(shop!= null){
                device.setShopName(shop.getShopName());
            }
        }
        model.addAttribute("device", device);

        return "module/device/welding/view";
    }


    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions(value = {"module:deviceWelding:add"}, logical = Logical.OR)
    public R save(@Valid DeviceWelding device) {
        Shop shop = shopService.findById(device.getShopId());
        if(shop!= null){
            device.setShopName(shop.getShopName());
        }

        if(device.getIsSelf() == 0){
            device.setState(1);//企业的直接激活
        }else{
            device.setState(0);// 未激活状态
        }

        FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
        if(fsrDevice!= null){
            device.setFsrDeviceName(fsrDevice.getName());
            device.setFsrBreakerId(fsrDevice.getId());
            device.setDeviceNum(fsrDevice.getId());
        }

        boolean bl = deviceWeldingService.save(device);
        if (bl) {
            String prefix = "";
            Province province = provinceService.findById(device.getProvId());
            if(province!= null){
                prefix += province.getNameCode();
            }

            City city = cityService.findById(device.getCityId());
            if(city != null){
                prefix += city.getNameCode();
            }

            device.setDeviceNo("T" + prefix +  StringUtil.LeftBuCode(device.getId()+"",6));
            if(fsrDevice!= null){
                fsrDevice.setDeviceId(device.getId());
                fsrDeviceService.updateById(fsrDevice);
            }
            try{
                String qrCode = "";
                String fileName = device.getDeviceName() + "_" + device.getId() +".jpg";
                String content = "https://en.zcchengyi.com/welding/qr?id=" + device.getId();
                System.out.println("content:  "+ content);

                String ss = device.getShopId() + "";
                if(device.getIsSelf() == 1){
                    ss = "self";
                }
                //上传头像到OSS
                String img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_DEVICE_WELDING_PHOTOS) + ss + "/"  + fileName;
                QRCodeUtilEx.createQrCodeImg(content,   "NO. " + device.getDeviceNo(), null,
                        uploadPath +"/"+ img_key, true);
                qrCode = img_key;
                device.setQrCodeUrl(qrCode);
                deviceWeldingService.updateById(device);
            }catch (Exception e){
                e.printStackTrace();
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions(value = {"module:deviceWelding:edit"}, logical = Logical.OR)
    public R update(@Valid DeviceWelding device) {

        Shop shop = shopService.findById(device.getShopId());
        if(shop!= null){
            device.setShopName(shop.getShopName());
        }


        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
        qw.eq("device_id",device.getId() );
        List<FsrDevice> fsrDevices = fsrDeviceService.list(qw);
        if(CollUtil.isNotEmpty(fsrDevices)){
            for (FsrDevice device1 : fsrDevices){
                device1.setDeviceId(0);
                fsrDeviceService.updateById(device1);
            }
        }

        if(device.getIsHasBreaker() == 1){
            FsrDevice fsrDevice = fsrDeviceService.findById(device.getFsrBreakerId());
            if(fsrDevice!= null){
                device.setFsrDeviceName(fsrDevice.getName());
                device.setFsrBreakerId(fsrDevice.getId());
                device.setDeviceNum(fsrDevice.getId());
                fsrDevice.setDeviceId(device.getId());
                fsrDeviceService.updateById(fsrDevice);
            }
        }

//        if(device.getProvId()!=null && device.getCityId()!=null){
//
//            String prefix = "";
//            Province province = provinceService.findById(device.getProvId());
//            if(province!= null){
//                prefix += province.getNameCode();
//            }
//
//            City city = cityService.findById(device.getCityId());
//            if(city != null){
//                prefix += city.getNameCode();
//            }
//
//            device.setDeviceNo("T" + prefix + StringUtil.LeftBuCode(device.getId()+"",6));
//        }

        deviceWeldingService.updateById(device);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions(value = {"module:deviceWelding:remove"}, logical = Logical.OR)
    public R remove( Integer id) {
        if (deviceWeldingService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }
}
